centos 7 设置 nginx 开机启动

创建开机启动命令脚本文件

1
vi /etc/init.d/nginx

在这个nginx文件中插入一下启动脚本代码,启动脚本代码来源网络复制,实测有效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#! /bin/bash
# chkconfig: - 85 15
PATH=/usr/local/nginx
DESC="nginx daemon"
NAME=nginx
DAEMON=$PATH/sbin/$NAME
CONFIGFILE=$PATH/conf/$NAME.conf
PIDFILE=$PATH/logs/$NAME.pid
scriptNAME=/etc/init.d/$NAME
set -e
[ -x "$DAEMON" ] || exit 0
do_start() {
$DAEMON -c $CONFIGFILE || echo -n "nginx already running"
}
do_stop() {
$DAEMON -s stop || echo -n "nginx not running"
}
do_reload() {
$DAEMON -s reload || echo -n "nginx can't reload"
}
case "$1" in
start)
echo -n "Starting $DESC: $NAME"
do_start
echo "."
;;
stop)
echo -n "Stopping $DESC: $NAME"
do_stop
echo "."
;;
reload|graceful)
echo -n "Reloading $DESC configuration..."
do_reload
echo "."
;;
restart)
echo -n "Restarting $DESC: $NAME"
do_stop
do_start
echo "."
;;
*)
echo "Usage: $scriptNAME {start|stop|reload|restart}" >&2
exit 3
;;
esac
exit 0

设置所有人都有对这个启动脚本nginx文件的执行权限

1
chmod a+x /etc/init.d/nginx

把nginx加入系统服务中

1
chkconfig --add nginx

把服务设置为开机启动

1
chkconfig nginx on

reboot重启系统生效

1
2
3
4
5
6
7
8
9
10
#启动nginx服务
systemctl start nginx.service
#停止nginx服务
systemctl stop nginx.service
#重启nginx服务

#同时也可以通过下面的命令进行服务重启,停止操作
service nginx restart
service nginx start
service nginx stop

如果服务启动的时候出现 Restarting nginx daemon: nginxnginx: [error] open() “/usr/local/nginx/logs/nginx.pid” failed (2: No such file or directory)
nginx not running 的错误,通过nginx -c 参数指定配置文件即可解决

1
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

如果服务启动中出现 nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use) 的错误,可以先通过service nginx stop 停止服务,再启动就好。